package groep3.ssc.helpers;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import android.util.Base64;

public class Encryption
{

    private static final String ALGORITHM = "AES";
    private static final byte[] keyValue = new byte[] { 'T', 'h', 'i', 's', 'I', 's', 'A', 'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y' };
    private static Key key;
    private static Cipher c;
    private static byte[] encValue;
    private static String encryptedValue;
    private static byte[] decordedValue;
    private static byte[] decValue;
    private static String decryptedValue;

    public static String encrypt(String valueToEnc) throws Exception
    {
        key = generateKey();
        c = Cipher.getInstance(ALGORITHM);
        c.init(Cipher.ENCRYPT_MODE, key);
        encValue = c.doFinal(valueToEnc.getBytes());
        encryptedValue = new String(Base64.encode(encValue, Base64.DEFAULT));
        // String encryptedValue = new BASE64Encoder().encode(encValue);
        return encryptedValue;
    }

    public static String decrypt(String encryptedValue) throws Exception
    {
        key = generateKey();
        c = Cipher.getInstance(ALGORITHM);
        c.init(Cipher.DECRYPT_MODE, key);
        decordedValue = Base64.decode(encryptedValue, Base64.DEFAULT);
        decValue = c.doFinal(decordedValue);
        decryptedValue = new String(decValue);
        return decryptedValue;
    }

    private static Key generateKey() throws Exception
    {
        key = new SecretKeySpec(keyValue, ALGORITHM);
        return key;
    }
}
